/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package utn.resumiderobilletes.ui.forms;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import utn.resumiderobilletes.entidades.Categoria;
import utn.resumiderobilletes.entidades.Cuenta;
import utn.resumiderobilletes.entidades.Movimiento;
import utn.resumiderobilletes.excepciones.ResumideroValidationException;
import utn.resumiderobilletes.listas.ListaGenerica;
import utn.resumiderobilletes.repositorios.Archivo;

/**
 *
 * @author Luciano
 */
public class FrmMovimiento extends javax.swing.JFrame {

    ListaGenerica<Cuenta> cuentas = Archivo.getDatos().getCuentas();
    ListaGenerica<Categoria> categorias = Archivo.getDatos().getCategorias();
    ListaGenerica<Movimiento> movimientos = Archivo.getDatos().getMovimientos();

    private FrmPrincipal frmParent;
    private Double monto;

    /**
     * Creates new form FrmMovimiento
     */
    public FrmMovimiento() {
        initComponents();

        cargarFormulario();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        radioDeposito = new javax.swing.JRadioButton();
        radioExtraccion = new javax.swing.JRadioButton();
        btGuardar = new javax.swing.JButton();
        txtMonto = new javax.swing.JTextField();
        comboCuenta = new javax.swing.JComboBox();
        comboCategoria = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("SansSerif", 1, 18)); // NOI18N
        jLabel1.setText("Crear Movimiento");

        jLabel2.setText("Cuenta:");

        jLabel3.setText("Monto $:");

        jLabel4.setText("Categoria/Motivo:");

        radioDeposito.setText("Deposito");
        radioDeposito.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioDepositoActionPerformed(evt);
            }
        });

        radioExtraccion.setText("Extracción");
        radioExtraccion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioExtraccionActionPerformed(evt);
            }
        });

        btGuardar.setText("Guardar");
        btGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGuardarActionPerformed(evt);
            }
        });

        comboCuenta.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        comboCategoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel5.setText("Operación:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtMonto, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(comboCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(comboCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(radioDeposito)
                                .addGap(18, 18, 18)
                                .addComponent(radioExtraccion))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btGuardar)
                        .addGap(186, 186, 186)))
                .addContainerGap(54, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(jLabel1)
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(comboCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioDeposito)
                    .addComponent(radioExtraccion)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addComponent(btGuardar)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void radioDepositoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioDepositoActionPerformed
        setRadios(true);
    }//GEN-LAST:event_radioDepositoActionPerformed

    private void radioExtraccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioExtraccionActionPerformed
        setRadios(false);
    }//GEN-LAST:event_radioExtraccionActionPerformed

    private void btGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGuardarActionPerformed
        try {
            Cuenta cuenta = (Cuenta) comboCuenta.getSelectedItem();
            Categoria categoria = (Categoria) comboCategoria.getSelectedItem();
            boolean isNumber = isnumber(txtMonto.getText());
            if (isNumber) {
                int idmov = movimientos.getCantidad() + 1;
                Movimiento mov = new Movimiento(idmov, cuenta.getNumeroCuenta(), categoria.getId(), monto, radioDeposito.isSelected());
                if (radioDeposito.isSelected()) {
                    cuenta.depositar(monto);
                } else {
                    if (cuenta.retirar(monto) == false) {
                        throw new ResumideroValidationException("No se pudo retirar el dinero de la cuenta. Compruebe el monto de la cuenta.");
                    }
                }
                categoria.agregar(mov);
                movimientos.agregar(mov);
                Archivo.guardar();
                frmParent.iniciarFormulario();
                JOptionPane.showMessageDialog(this, "El Movimiento se creo exitosamente!!!", "Error", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } else {
                JOptionPane.showMessageDialog(this, "El monto tiene que ser un numero valido mayor que 0.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (ResumideroValidationException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btGuardarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmMovimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmMovimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmMovimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmMovimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmMovimiento().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btGuardar;
    private javax.swing.JComboBox comboCategoria;
    private javax.swing.JComboBox comboCuenta;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JRadioButton radioDeposito;
    private javax.swing.JRadioButton radioExtraccion;
    private javax.swing.JTextField txtMonto;
    // End of variables declaration//GEN-END:variables

    private void cargarFormulario() {
        txtMonto.setText("");
        setRadios(true);
        cargarCategorias();
        cargarCuentas();
    }

    private void cargarCategorias() {
        comboCategoria.removeAllItems();
        for (Categoria categoria : categorias) {
            comboCategoria.addItem(categoria);
        }
        comboCategoria.repaint();
    }

    public void setPadre(FrmPrincipal pPadre) {
        frmParent = pPadre;
    }

    private void setRadios(boolean value) {
        radioDeposito.setSelected(value);;
        radioExtraccion.setSelected(!value);
    }

    private void cargarCuentas() {
        comboCuenta.removeAllItems();
        for (Cuenta cuenta : cuentas) {
            comboCuenta.addItem(cuenta);
        }
        comboCuenta.repaint();
    }

    private boolean isnumber(String text) {
        try {
            monto = Double.valueOf(text);
            return monto > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

}
